package com.jwkj.collector.server;


import com.jwkj.collector.master.TcpRTUMaster;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CollectorServer {

    private static Logger logger = Logger.getLogger(CollectorServer.class);
    private static ConcurrentMap<String, TcpRTUMaster> sockets = new ConcurrentHashMap<>();
    private static CollectorServer server;
    private ServerSocket serverSocket;
    private ExecutorService executorService;
    private final int POOL_SIZE = 10;
    private int port = 9527;

    public static ConcurrentMap getSockets() {
        return sockets;
    }

    public static CollectorServer getInstance() {
        if (null == server) {
            try {
                server = new CollectorServer();
            } catch (IOException e) {
                logger.error("-------------------采集服务启动失败----------------", e);
            }
        }
        return server;
    }

    public CollectorServer() throws IOException {
        serverSocket = new ServerSocket(port);
        executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
        logger.debug("-------------------采集服务已启动----------------");
    }

    public void start() {
        while (true) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                logger.debug("-------------------监听到新的客户端连接----------------");
                sockets.put(socket.getInetAddress().getHostAddress(), new TcpRTUMaster(socket));
            } catch (Exception e) {
                logger.error("-------------------采集服务器启动失败------------------", e);
            }
        }
    }


    public enum COMMAND {
        COLLECT, CONTROL, INIT;
    }

}
